﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace DIProject.ReceptionGoods
{
    public partial class WaybillsImportList : Form,DIProject.Util.IDateRange
    {
        public WaybillsImportList()
        {
            InitializeComponent();
        }
                
        public Int32 CurrendDocId
        {
            get
            {
                if (this.lbNaklList.Items.Count < 1)
                {
                    MessageBox.Show("Не выбрано ни одной накладной");
                    return Int32.MinValue;
                }
                Int32 result = (Int32)lbNaklList.SelectedValue;
                return result;
            }
        }
        #region IDateRange Members
        private DateTime _beginDate = DateTime.Now;
        public DateTime BeginDate
        {
            get
            {
                return _beginDate;
            }
            set
            {
                _beginDate = value;
                this.IsSelected = true;
            }
        }
        private DateTime _endDate = DateTime.Now;
        public DateTime EndDate
        {
            get
            {
                return _endDate;
            }
            set
            {
                _endDate = value;
                this.IsSelected = true;
            }
        }
        private bool _isSelected = false;
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                _isSelected = value;
            }
        }

        #endregion
        private object GetData(Int32 docId)
        {
            DataSets.waybillsDataTableAdapters.CurrentNaklTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.CurrentNaklTableAdapter();
            DataSets.waybillsData.CurrentNaklDataTable result = adapter.GetData(docId);
            _data = result;
            _data.CurrentNaklRowChanged += new DIProject.DataSets.waybillsData.CurrentNaklRowChangeEventHandler(_data_CurrentNaklRowChanged);
            
            return result;
        }

        void _data_CurrentNaklRowChanged(object sender, DIProject.DataSets.waybillsData.CurrentNaklRowChangeEvent e)
        {
            
        }
        private void UpdatePrice()
        {
            double d;
            if (!double.TryParse(txbMarkUp.Text, out d))
            {
                MessageBox.Show("Ошибка");
            }
            //double d1 = d / 100 + 1;
            foreach (DataRowView drv in this.CurrentDataView)
            {
                DataSets.waybillsData.CurrentNaklRow cr = drv.Row as DataSets.waybillsData.CurrentNaklRow;
                if (!cr.IsSupplierPriceNull())
                {
                   // byte nds = 0;
                   // if (!cr.IsNDSTaxNull())
                   //     nds = cr.NDSTax;
                  //  decimal ss = cr.SupplierPrice;
                  //  decimal tmp = ss * nds / 100;
                  //  tmp = Math.Round(tmp, 2,MidpointRounding.AwayFromZero);
                 //   tmp = cr.SupplierPrice + tmp;
                   // cr.RetailPrice = Convert.ToDecimal(Convert.ToDecimal(d1) * tmp);
                    cr.RetailMarkup = d;
                    cr.RetailPrice = cr.SupplierPrice * Convert.ToDecimal((1 + d / 100));
                }
                else
                {
                    MessageBox.Show("Для товара " + cr.FullName + "не указана цена поставщика");
                }
                this.NDSRun(cr);
            }
        }
       
                
        #region калькуляция
        private bool _isPrevisionPrice = false;
        private DataSets.waybillsData.CurrentNaklDataTable _data;
        /// <summary>
        /// текущие данные
        /// </summary>
        public DataSets.waybillsData.CurrentNaklDataTable CurrentData
        {
            get
            {
                //CalculatePrevisionPrice(_data);                
                return _data;
            }
        }
        private void CalculatePrevisionPrice(DataSets.waybillsData.CurrentNaklDataTable tlb)
        {
            if (tlb == null)
                return;
            if (ddlDepart2.ComboBox.SelectedValue == null)
                return;
            Int32 dId = (Int32)ddlDepart2.ComboBox.SelectedValue;
            DataSets.waybillsDataTableAdapters.NklQueries query = new DIProject.DataSets.waybillsDataTableAdapters.NklQueries();
            foreach (DataSets.waybillsData.CurrentNaklRow cr in tlb.Rows)
            {
                object obj = query.previsionPrice(cr.GoodsId,dId);
                object obj2 = query.previsionPrice2(cr.GoodsId, dId);
                if ((!Convert.IsDBNull(obj) && obj != null))
                {
                    cr.PrevisionPrice = Convert.ToDecimal(obj);                    
                }
                if ((!Convert.IsDBNull(obj2) && obj2 != null))
                {                    
                    cr.PrevisionPrice2 = Convert.ToDecimal(obj2);
                }
            }
            _isPrevisionPrice = true;
        }
        public DataView CurrentDataView
        {
            get
            {
                return CurrentData.DefaultView;
            }
        }
        private void cliarFilter_Click(object sender, EventArgs e)
        {
            CurrentDataView.RowFilter = string.Empty;
            CurrentFilter = string.Empty;
            nkldDateGrid.DataSource = CurrentDataView;
            toolStripTextBox1.Text = string.Empty;
            filtrLabel.Text = string.Empty;
        }
        private string _curFilter;

        public string CurrentFilter
        {
            get { return _curFilter; }
            set { _curFilter = value; }
        }
        private void MessageFilterError()
        {
            MessageBox.Show("Ошибка в фильтре!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        /// <summary>
        /// переделываем фильтер
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="filterValue"></param>
        private void ReorganizeFilter(DataGridViewColumn col, string filterValue)
        {
            string pattern = "\\s*(?<eq>>=|<=|>|<)\\s*((?<val1>\\d+,\\d*)|(?<val2>\\d+))";
            Type t = col.ValueType;
            Type tString = typeof(string);
            
            if (t == tString)
            {
                return;
            }
            else
            {
                Regex re = new Regex(pattern);
                Match m = re.Match(filterValue);
                if (m == null)
                    MessageFilterError();

            }
            CurrentFilter = col.DataPropertyName + filterValue;
           /* if (string.IsNullOrEmpty(CurrentFilter))
            {
                CurrentFilter = col.DataPropertyName + filterValue;
            }
            else
            {
                CurrentFilter += " AND " + col.DataPropertyName + filterValue;
            }*/            
            CurrentDataView.RowFilter = CurrentFilter;
            nkldDateGrid.DataSource = CurrentDataView;
            //DataGridViewColumn col = nkldDateGrid.Columns[colI];
            filtrLabel.Text = col.HeaderText + filterValue;
        }
        private void NDSRun(DataSets.waybillsData.CurrentNaklRow cr)
        {
            //cr.RetailPriceWithNDS = Convert.ToDecimal(cr.RetailPrice * Convert.ToDecimal((1 + Convert.ToDouble(cr.NDSTax) / 100)));
        }
        /// <summary>
        /// округляем до 10 копеек
        /// </summary>
        private void RaundPrice()
        {
            CurrentDataView.RowFilter = string.Empty;
            foreach (DataSets.waybillsData.CurrentNaklRow cr in this.CurrentData.Rows)
            {
                bool b = false;
                if (!cr.IsGNVLSNull())
                {
                    b = cr.GNVLS;
                }
                if (cr.IsRetailPriceNull())
                {
                    MessageBox.Show("Нет розничной цены для " + cr.FullName);
                    return;
                }
                //Округляем в меньшую сторону
                if (b)
                {
                    decimal d = cr.RetailPrice;
                    d = d * 10;
                    d = Math.Floor(d);
                    d = d / 10;
                    cr.RetailPrice = d;

                }
                //В большую
                else
                {
                    decimal d = cr.RetailPrice;
                    d = Math.Round(d, 1);
                    cr.RetailPrice = d;

                }
            }
        }
        private void RaundPrice1()
        {
            CurrentDataView.RowFilter = string.Empty;
            foreach (DataSets.waybillsData.CurrentNaklRow cr in this.CurrentData.Rows)
            {
                bool b = false;
                if (!cr.IsGNVLSNull())
                {
                    b = cr.GNVLS;
                }
                if (cr.IsRetailPriceNull())
                {
                    MessageBox.Show("Нет розничной цены для " + cr.FullName);
                    return;
                }
                //Округляем в меньшую сторону
                if (b)
                {
                    decimal d = cr.RetailPrice;
                  //  d = d * 10;
                    d = Math.Floor(d);
                  //  d = d / 10;
                    cr.RetailPrice = d;

                }
                //В большую
                else
                {
                    decimal d = cr.RetailPrice;
                    d = Math.Round(d, 0);
                    cr.RetailPrice = d;

                }
            }
        }
        /// <summary>
        /// расценка жизненно необходимых лек. средств
        /// </summary>
        private void RaundGNVLS()
        {
            CurrentDataView.RowFilter = string.Empty;
            foreach (DataSets.waybillsData.CurrentNaklRow cr in this.CurrentData.Rows)
            {
                if (cr.IsSupplierPriceNull())
                {
                    MessageBox.Show("Нет цены поставщика для " + cr.FullName);
                    continue;
                }
                if (!cr.IsGNVLSNull())
                {
                    if (cr.GNVLS)
                    {
                        if (!cr.IsRetailPriceNull())
                        {
                            if (!cr.IsRetailMarkupNull())
                            {
                                if (cr.RetailMarkup > 25.0)
                                {
                                    cr.RetailMarkup = 25;
                                    decimal d1 = cr.SupplierPrice;
                                    decimal gnlvs1 = d1 * Convert.ToDecimal(1.25);
                                    cr.RetailPrice = gnlvs1;
                                }
                                continue;
                            }
                        }
                        decimal d = cr.SupplierPrice;
                        decimal gnlvs = d * Convert.ToDecimal(1.25);
                        cr.RetailPrice = gnlvs;
                        this.NDSRun(cr);
                        cr.RetailMarkup = 25;
                    }
                }
            }
        }
        private void RaundGroup()
        {
            CurrentDataView.RowFilter = string.Empty;
            foreach (DataSets.waybillsData.CurrentNaklRow cr in this.CurrentData.Rows)
            {
                DataSets.waybillsDataTableAdapters.NklQueries query = new DIProject.DataSets.waybillsDataTableAdapters.NklQueries();
                object obj = query.GoodsMarkUp(cr.GoodsId);
                //есть наценка для группы
                if ((!Convert.IsDBNull(obj)) && (obj != null))
                {
                    double d = Convert.ToDouble(obj);
                    cr.RetailMarkup = d;
                    if (cr.IsSupplierPriceNull())
                    {
                        MessageBox.Show("Нет цены поставщика для " + cr.FullName);
                        return;
                    }
                    decimal fin = cr.SupplierPrice * Convert.ToDecimal((1 + d / 100));
                    cr.RetailPrice = fin;
                    this.NDSRun(cr);
                }
            }
        }
        private void CalculateStatistik()
        {
            CurrentDataView.RowFilter = string.Empty;
            double summWithNDS = 0;
            double summNoNDS = 0;
            double percentNazen = 0;
            double supplierSumm = 0;
            double middleweightsum = 0.0;
            double middleweightsumnotax = 0.0;

            foreach (DataSets.waybillsData.CurrentNaklRow cr in this.CurrentData.Rows)
            {
                if (!cr.IsRetailPriceNull())
                {
                    double d = 0;
                    byte ndsV = 0;
                    if (!cr.IsNDSTaxNull())
                    {
                        ndsV = cr.NDSTax;
                    }
                    d = Convert.ToDouble(cr.RetailPrice * cr.Count);
                    d = (100 * d) / (100 + ndsV);
                    summWithNDS += Convert.ToDouble(cr.RetailPrice * cr.Count);
                    summNoNDS += Math.Round(d, 2);
                }
                if (!cr.IsRetailMarkupNull())
                {
                    percentNazen += cr.RetailMarkup;
                    if (!cr.IsSupplierSumNOTAXNull())
                    {
                        middleweightsumnotax += (double)cr.SupplierSumNOTAX;
                        middleweightsum += cr.RetailMarkup * (double)cr.SupplierSumNOTAX;
                    }
                }
                if (!cr.IsSupplierPriceNull())
                {
                   /* byte nds = 0;
                    if (!cr.IsNDSTaxNull())
                        nds = cr.NDSTax;
                    decimal ss = cr.SupplierPrice;
                    decimal tmp = ss * nds / 100;
                    tmp = Math.Round(tmp, 2,MidpointRounding.AwayFromZero);*/
                    supplierSumm += Convert.ToDouble(cr.SupplierPrice * cr.DocQntty);
                }
                else
                {
                    MessageBox.Show("Для товара " + cr.FullName + "не указана цена поставщика");
                }
            }//for
            
            // Особо считаем средневзвешенную наценку
            /*
            Int32 tmp = (Int32)lbNaklList.SelectedValue;
            DataSets.waybillsDataTableAdapters.RetailMarkupWeightTableAdapter rmwta = new DIProject.DataSets.waybillsDataTableAdapters.RetailMarkupWeightTableAdapter();
            rmwta.Fill(waybillsData.RetailMarkupWeight, tmp);
            double totalweight = (float)this.CurrentData.Count; //waybillsData.RetailMarkupWeight.Count;
            double mwsum = 0.0;
            foreach (DataSets.waybillsData.RetailMarkupWeightRow rmwrow in waybillsData.RetailMarkupWeight)
            {
                if(!rmwrow.IsRetailMarkupNull() && !rmwrow.IsMarkupWeightNull())
                mwsum += rmwrow.RetailMarkup * (rmwrow.MarkupWeight / totalweight);
            }*/
            
            double mwsum = 0;
            if(middleweightsumnotax > 0 )
                mwsum = middleweightsum / middleweightsumnotax;
                
            lbNoNDS.Text = "Сумма без НДС " + summNoNDS.ToString();
            lbWithNDS.Text = "Сумма с НДС " + summWithNDS.ToString();
            lbPercentAvg.Text = "Средний процент наценки " + (percentNazen / CurrentData.Rows.Count).ToString();
            lblSupplaerSumm.Text = "Сумма накладной " + supplierSumm.ToString();
            lbRowCount.Text = "Количество строк " + this.CurrentData.Count.ToString();
            lbMiddleWeightSum.Text = "СРЕДНЕВЗВЕШЕННЫЙ процент наценки " + mwsum.ToString();
        }
        #endregion
        #region обработка событий на форме
       
        private void InitDepartments()
        {
            DataSets.SettingsTableAdapters.DepartmentsTableAdapter adapt = new DIProject.DataSets.SettingsTableAdapters.DepartmentsTableAdapter();
            DataSets.Settings.DepartmentsDataTable data = adapt.GetData();
            ComboBox cb = ddlDepartment.ComboBox;
            cb.DisplayMember = "Name";
            cb.ValueMember = "Id";
            cb.DataSource = data;
            DataSets.SettingsTableAdapters.DepartmentsTableAdapter adapt1 = new DIProject.DataSets.SettingsTableAdapters.DepartmentsTableAdapter();
            DataSets.Settings.DepartmentsDataTable data1 = adapt1.GetData();
            ComboBox cb1 = ddlDepart2.ComboBox;
            cb1.DisplayMember = "Name";
            cb1.ValueMember = "Id";
            cb1.DataSource = data1;
        }
        private void WaybillsImportList_Load(object sender, EventArgs e)
        {
            InitDepartments();
            DataSets.SettingsTableAdapters.ContragentsTableAdapter adapter = new DIProject.DataSets.SettingsTableAdapters.ContragentsTableAdapter();
            DataSets.Settings.ContragentsDataTable cdt = adapter.GetData();
            DataSets.Settings.ContragentsRow cr = cdt.NewContragentsRow();
            cr.Id = -100;
            cr.Name = "Выберите поставщика";
            cdt.Rows.InsertAt(cr, 0);
            cbContragents.ComboBox.DisplayMember = "Name";
            cbContragents.ComboBox.ValueMember = "Id";
            cbContragents.ComboBox.DataSource = cdt;
            filtrLabel.Text = string.Empty;
            VerifyPRManualNaklSumTable();
        }
        private void VerifyPRManualNaklSumTable()
        {
            try
            {
                using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(DIProject.Properties.Settings.Default.DIAptekaConnectionString))
                {
                    System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(
                        "SELECT OBJECT_ID('PR.ManualNaklSum', 'U')", connection);
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    object searchtable = command.ExecuteScalar();
                    if (searchtable is DBNull)
                    {
                        MessageBox.Show("Не найдена таблица PR.ManualNaklSum!");
                        /*command.CommandText = "CREATE TABLE [PR].[ManualNaklSum] ( Id int IDENTITY(1,1) PRIMARY KEY, DocId int, ContragentId int, DepartmentId int, Summa decimal (19,2), MD datetime, MW varchar(50))";
                        int affected = command.ExecuteNonQuery();
                        if(affected != 1)
                            throw new Exception("НЕ УДАЛОСЬ СОЗДАТЬ ТАБЛИЦУ PR.ManualNaklSum!");*/
                    }
                    // Если таблица есть-ничё не делаем
                }
            }
            catch (System.Data.SqlClient.SqlException se)
            {
                string eemsg = se.Message;
                eemsg = eemsg.Replace('\r', ' '); eemsg = eemsg.Replace('\n', ' ');
                MessageBox.Show("ОШИБКА " + se.Procedure + Environment.NewLine +
                                 eemsg, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception e1)
            {
                string eemsg = e1.Message;
                eemsg = eemsg.Replace('\r', ' '); eemsg = eemsg.Replace('\n', ' ');
                MessageBox.Show("ОШИБКА " + e1.Source + Environment.NewLine +
                                 eemsg, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }             
        }
        private void RefreshNkldList()
        {
            SaveAll();
            ToolStripComboBox tscb = cbContragents;
            ComboBox cb = tscb.ComboBox;
            DataRowView drv = cb.SelectedItem as DataRowView;
            DataSets.Settings.ContragentsRow cr = drv.Row as DataSets.Settings.ContragentsRow;
            lblContragent.Text = cr.Name;
            Int32 tmp = (Int32)cb.SelectedValue;
            if (tmp == Int32.MinValue)
                return;
            cb = ddlDepartment.ComboBox;
            drv = cb.SelectedItem as DataRowView;
            DataSets.Settings.DepartmentsRow dr = drv.Row as DataSets.Settings.DepartmentsRow;
            Int32 deptId = dr.Id;
            DataSets.waybillsDataTableAdapters.DocumentsTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.DocumentsTableAdapter();
            DataSets.waybillsData.DocumentsDataTable doc = adapter.GetData(tmp, deptId);
            lbNaklList.DataSource = doc;
            sg = null;
        }
        
        private decimal SummaWONDS = 0;
        private decimal SummaWithNDS10 = 0;
        private decimal SummaWithNDS18 = 0;
        private decimal SummaNDS10 = 0;
        private decimal SummaNDS18 = 0;
        private bool    NewRecord = true;
        private string  ThisNaklNo = string.Empty;
      
        public void lbNaklList_DoubleClick(object sender, EventArgs e)
        {
            SaveAll();
            ListBox lb = sender as ListBox;
            Int32 tmp = (Int32)lb.SelectedValue;            
            ThisNaklNo = lb.Text;
            nkldDateGrid.VirtualMode = false;
            DataSets.waybillsData.CurrentNaklDataTable cn = this.GetData(tmp) as DataSets.waybillsData.CurrentNaklDataTable;
            if(cn!=null)
                CalculatePrevisionPrice(cn);
            nkldDateGrid.DataSource = cn;
            nkldDateGrid.VirtualMode = true;
            this._isPrevisionPrice = false;
            filtrLabel.Text = string.Empty;
            // Подгружаем вручную введённую сумму накладной из PR.ManualNaklSum
            #region Пришил кобыле хвост
            ToolStripComboBox tscb = cbContragents;
            ComboBox cb = tscb.ComboBox;
            DataRowView drv = cb.SelectedItem as DataRowView;
            DataSets.Settings.ContragentsRow cr = drv.Row as DataSets.Settings.ContragentsRow;            
            Int32 tmpcontragentid = (Int32)cb.SelectedValue;
            
            string qstr = string.Format(
                "SELECT SummaWONDS, SummaWithNDS10, SummaWithNDS18, SummaNDS10, SummaNDS18 " + 
                "FROM PR.ManualNaklSum WHERE DocId={0} AND ContragentId={1}", tmp, tmpcontragentid);
            try
            {
                using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(DIProject.Properties.Settings.Default.DIAptekaConnectionString))
                {
                    System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(qstr, connection);
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    System.Data.SqlClient.SqlDataReader sdr = command.ExecuteReader();
                    
                    if (sdr.HasRows)
                    {
                        Int32 sumwondsindex     = sdr.GetOrdinal("SummaWONDS");
                        Int32 sumnds10index     = sdr.GetOrdinal("SummaNDS10");
                        Int32 sumwithnds10index = sdr.GetOrdinal("SummaWithNDS10");
                        Int32 sumnds18index     = sdr.GetOrdinal("SummaNDS18");
                        Int32 sumwithnds18index = sdr.GetOrdinal("SummaWithNDS18");
                        
                        while (sdr.Read())
                        {
                            if (sdr.IsDBNull(sumwondsindex))
                                SummaWONDS = 0;
                            else
                                SummaWONDS = sdr.GetDecimal(sumwondsindex);
                            if (sdr.IsDBNull(sumnds10index))
                                SummaNDS10 = 0;
                            else
                                SummaNDS10 = sdr.GetDecimal(sumnds10index);
                            if (sdr.IsDBNull(sumwithnds10index))
                                SummaWithNDS10 = 0;
                            else
                                SummaWithNDS10 = sdr.GetDecimal(sumwithnds10index);
                            if (sdr.IsDBNull(sumnds18index))
                                SummaNDS18 = 0;
                            else
                                SummaNDS18 = sdr.GetDecimal(sumnds18index);
                            if (sdr.IsDBNull(sumwithnds18index))
                                SummaWithNDS18 = 0;
                            else
                                SummaWithNDS18 = sdr.GetDecimal(sumwithnds18index);
                        }
                        NewRecord = false;
                    }
                    else // 
                    { 
                        SummaWONDS = 0;
                        SummaWithNDS10 = 0;
                        SummaWithNDS18 = 0;
                        SummaNDS10 = 0;
                        SummaNDS18 = 0;
                        NewRecord = true;
                    }
                }
            }
            catch (System.Data.SqlClient.SqlException se)
            {
                string eemsg = se.Message;
                eemsg = eemsg.Replace('\r', ' '); eemsg = eemsg.Replace('\n', ' ');
                MessageBox.Show("ОШИБКА " + se.Procedure + Environment.NewLine +
                                 eemsg, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception e1)
            {
                string eemsg = e1.Message;
                eemsg = eemsg.Replace('\r', ' '); eemsg = eemsg.Replace('\n', ' ');
                MessageBox.Show("ОШИБКА " + e1.Source + Environment.NewLine +
                                 eemsg, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            #endregion
        }

        private void EditNaklSumtoolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentDataView == null) return;
                CurrentDataView.RowFilter = string.Empty;
                if (this.CurrentData.Rows.Count == 0) return;
            }
            catch { return; }
            decimal naklsum = 0;
            if (NewRecord)
            {
                SummaWONDS = 0;
                SummaWithNDS10 = 0;
                SummaWithNDS18 = 0;
                SummaNDS10 = 0;
                SummaNDS18 = 0;

                foreach (DataSets.waybillsData.CurrentNaklRow cr in this.CurrentData.Rows)
                {
                    if (!cr.IsSupplierPriceNull())
                    {
                        naklsum += cr.SupplierPrice * cr.DocQntty;
                        if (!cr.IsNDSTaxNull())
                        {
                            if (cr.NDSTax == 10)
                                SummaWithNDS10 += cr.SupplierPrice * cr.DocQntty;
                            else
                                if (cr.NDSTax == 18)
                                    SummaWithNDS18 += cr.SupplierPrice * cr.DocQntty;
                            if (!cr.IsNDSValueNull())
                            {
                                if (cr.NDSTax == 10)
                                    SummaNDS10 += cr.NDSValue;
                                else
                                    if (cr.NDSTax == 18)
                                        SummaNDS18 += cr.NDSValue;
                            }
                        }                        
                    }
                    else
                    {
                        MessageBox.Show("Для товара " + cr.FullName + "не указана цена поставщика");
                    }
                    if (!cr.IsSupplierSumNOTAXNull() && !cr.IsNDSValueNull())
                    {
                        // считаем чистую сумму без НДС
                        SummaWONDS += cr.SupplierSumNOTAX - cr.NDSValue;
                    }
                }//for
            }//if new
            
            EditNaklSumm ensform = new EditNaklSumm();
            ensform.SumNDS10 = SummaNDS10;
            ensform.SumNDS18 = SummaNDS18;
            ensform.SumWithNDS10 = SummaWithNDS10;
            ensform.SumWithNDS18 = SummaWithNDS18;
            ensform.SumWONDS = SummaWONDS;
            ensform.NaklNo = ThisNaklNo;
            if (ensform.ShowDialog() != DialogResult.OK) return;
            if (ensform.SumChanged == false) return;

            ListBox lb = lbNaklList;
            Int32 tmp = (Int32)lb.SelectedValue;

            ToolStripComboBox tscb = cbContragents;
            ComboBox cb = tscb.ComboBox;
            DataRowView drv = cb.SelectedItem as DataRowView;
            //DataSets.Settings.ContragentsRow cr1 = drv.Row as DataSets.Settings.ContragentsRow;
            Int32 tmpcontragentid = (Int32)cb.SelectedValue;
            System.Data.SqlClient.SqlDataReader r = null;
            string qstr;
            DateTime MD = DateTime.Now;
            string mdate = String.Format("{0}{1}{2} {3}:{4}:{5}", MD.Year, MD.Month.ToString("D2"), MD.Day.ToString("D2"), MD.Hour.ToString("D2"), MD.Minute.ToString("D2"), MD.Second.ToString("D2")); ;            
            string SummaWONDSstr = ensform.SumWONDS.ToString();
            string SummaWithNDS10str = ensform.SumWithNDS10.ToString();
            string SummaWithNDS18str = ensform.SumWithNDS18.ToString();
            string SummaNDS10str = ensform.SumNDS10.ToString();
            string SummaNDS18str = ensform.SumNDS18.ToString();            
            SummaWONDSstr = SummaWONDSstr.Replace(',', '.');
            SummaWithNDS10str = SummaWithNDS10str.Replace(',', '.');
            SummaWithNDS18str = SummaWithNDS18str.Replace(',', '.');
            SummaNDS10str = SummaNDS10str.Replace(',', '.');
            SummaNDS18str = SummaNDS18str.Replace(',', '.');

            if (NewRecord) // INSERT new data
                qstr = string.Format(
                    "INSERT INTO [PR].[ManualNaklSum] (DocId, ContragentId, SummaWONDS, SummaWithNDS10, " +
                    "SummaWithNDS18, SummaNDS10, SummaNDS18, MD, MW) VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6}, CAST(\'{7}\' AS datetime), '{8}')",
                    tmp, tmpcontragentid, SummaWONDSstr, SummaWithNDS10str, SummaWithNDS18str,
                    SummaNDS10str, SummaNDS18str, mdate, "MW");
            else
                qstr = string.Format("UPDATE [PR].[ManualNaklSum] SET [MD]=CAST(\'{1}\' AS datetime), "+
                                     "[SummaWONDS]={2}, [SummaWithNDS10]={3}, [SummaWithNDS18]={4}, [SummaNDS10]={5}, [SummaNDS18]={6} WHERE [DocId]={7} AND [ContragentId]={8}",
                                      0, mdate, 
                                      SummaWONDSstr, SummaWithNDS10str, SummaWithNDS18str, SummaNDS10str, SummaNDS18str,
                                      tmp, tmpcontragentid);
            try
            {
                using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(DIProject.Properties.Settings.Default.DIAptekaConnectionString))
                {
                    System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(qstr, connection);
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    r = command.ExecuteReader();
                    if (r.RecordsAffected <= 0)
                        throw new Exception("НЕ УДАЛОСЬ СОЗДАТЬ/ИЗМЕНИТЬ ЗАПИСЬ ОБ ОПЛАТЕ В PR.ManualNaklSum!");
                    if (!NewRecord)
                    {  // апдейт
                        SummaNDS10 = ensform.SumNDS10;
                        SummaNDS18 = ensform.SumNDS18;
                        SummaWithNDS10 = ensform.SumWithNDS10;
                        SummaWithNDS18 = ensform.SumWithNDS18;
                        SummaWONDS = ensform.SumWONDS;
                    }
                    NewRecord = false;
                }
            }
            catch (System.Data.SqlClient.SqlException se)
            {
                string eemsg = se.Message;
                eemsg = eemsg.Replace('\r', ' '); eemsg = eemsg.Replace('\n', ' ');
                MessageBox.Show("ОШИБКА " + se.Procedure + Environment.NewLine +
                                 eemsg, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception e1)
            {
                string eemsg = e1.Message;
                eemsg = eemsg.Replace('\r', ' '); eemsg = eemsg.Replace('\n', ' ');
                MessageBox.Show("ОШИБКА " + e1.Source + Environment.NewLine +
                                 eemsg, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            ToolStripTextBox tb = sender as ToolStripTextBox;
            string str = tb.TextBox.Text;
            if (e.KeyChar == '\r')
            {
                if (colI == Int32.MaxValue)
                    return;
                DataGridViewColumn col = nkldDateGrid.Columns[colI];
                ReorganizeFilter(col, str);
                this.cms.Hide();
            }
        }
        Int32 colI = Int32.MaxValue;
        private void nkldDateGrid_MouseDown(object sender, MouseEventArgs e)
        {
            colI = this.nkldDateGrid.HitTest(e.X, e.Y).ColumnIndex;           
        }
        
        private void btnRecompute_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txbMarkUp.Text))
            {
                MessageBox.Show("Необходимо заполнить значение наценки!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txbMarkUp.Focus();
                return;
            }
            UpdatePrice();
            //CalculateStatistik();
        }
        
        private void txbMarkUp_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\b')
                return;
            double d;
            if (!double.TryParse(txbMarkUp.Text + e.KeyChar, out d))
            {
                System.Console.Beep(100, 100);
                e.Handled = true;
            }
        }

        private void nkldDateGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            
        }
        

        private void nkldDateGrid_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            DataGridViewRow dgvr = dgv.Rows[e.RowIndex];
            DataRowView drv = dgvr.DataBoundItem as DataRowView;
            DataSets.waybillsData.CurrentNaklRow crw = drv.Row as DataSets.waybillsData.CurrentNaklRow;
            if (!crw.IsGNVLSNull())
            {
                if (crw.GNVLS)
                {
                    dgvr.DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            this.RaundPrice();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            this.RaundGNVLS();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (nkldDateGrid.Rows.Count < 1)
            {
                MessageBox.Show("Нет строк в накладной");
                return;
            }
            CalculateStatistik();
        }
        /// <summary>
        /// в продажу
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (nkldDateGrid.Rows.Count < 1)
            {
                MessageBox.Show("Нет строк в накладной");
                return;
            }
            this.ToTrade();
        }
        #endregion
        #region в продажу
        private void ToTrade()
        {
            CurrentDataView.RowFilter = string.Empty;
            Int32 errCount = 0;
            foreach (DataSets.waybillsData.CurrentNaklRow cr in this.CurrentData.Rows)
            {
                if (!this.UpdateRow(cr))
                    errCount++;
                if (errCount > 3)
                    return;
            }
        }
        /// <summary>
        /// заводим партию
        /// </summary>
        /// <param name="cr"></param>
        /// <returns></returns>
        private bool UpdateRow(DataSets.waybillsData.CurrentNaklRow cr)
        {
            DataSets.waybillsData.SupplierInvoiceLinesUpdateDataTable dt;
           // DataSets.waybillsData.PartiesUpdateDataTable pdt;
            DataSets.waybillsData.SupplierInvoiceLinesUpdateRow sr = null;
            DateTime MD = DateTime.Now;
            try
            {
                DataSets.waybillsDataTableAdapters.SupplierInvoiceLinesUpdateTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.SupplierInvoiceLinesUpdateTableAdapter();
                decimal? ManufacturerPrice = null;
                if (!cr.IsManufacturerPriceNull())
                    ManufacturerPrice = cr.ManufacturerPrice;
                double? ImportMarkup = null;
                if (!cr.IsImportMarkupNull())
                    ImportMarkup = cr.ImportMarkup;
                double? SupplierMarkup = null;
                if (!cr.IsSupplierMarkupNull())
                    SupplierMarkup = cr.SupplierMarkup;
                string BatchNumber = null;
                if (!cr.IsBatchNumberNull())
                    BatchNumber = cr.BatchNumber;
                DateTime? ReadyBefore = null;
                if (!cr.IsReadyBeforeNull())
                    ReadyBefore = cr.ReadyBefore;
                DateTime? MadeDate = null;
                if (!cr.IsMadeDateNull())
                    MadeDate = cr.MadeDate;
                decimal? ReestrPrice = null;
                if (!cr.IsReestrPriceNull())
                    ReestrPrice = cr.ReestrPrice;
                DateTime? ReestrDate = null;
                if (!cr.IsReestrDateNull())
                    ReestrDate = cr.ReestrDate;
                string GTDNumber = null;
                if (!cr.IsGTDNumberNull())
                    GTDNumber = cr.GTDNumber;
                string CertificateNumber = null;
                if (!cr.IsCertificateNumberNull())
                    CertificateNumber = cr.CertificateNumber;
                DateTime? CertificateDate = null;
                if (!cr.IsCertificateDateNull())
                    CertificateDate = cr.CertificateDate;
                Int32? CertificateOrgId = null;
                if (!cr.IsCertificateOrgIdNull())
                    CertificateOrgId = cr.CertificateOrgId;
                double? RetailMarkup1 = null;
                if (!cr.IsRetailMarkupNull())
                    RetailMarkup1 = cr.RetailMarkup;
                if (cr.IsRetailPriceNull())
                    throw new Util.DIException("Не задана розничная цена!");
                decimal? SupplierPrice = null;
                if (!cr.IsSupplierPriceNull())
                    SupplierPrice = cr.SupplierPrice;
                decimal? NDSValue = null;
                if (!cr.IsNDSValueNull())
                    NDSValue = cr.NDSValue;
                byte? NDSTax = null;
                if (!cr.IsNDSTaxNull())
                    NDSTax = cr.NDSTax;
                decimal? SupplierSumNOTAX = null;
                if (!cr.IsSupplierSumNOTAXNull())
                    SupplierSumNOTAX = cr.SupplierSumNOTAX;
                dt = adapter.GetData(cr.GoodsId, cr.BarCode, cr.DocQntty, cr.Count, cr.SupplierGoodsId, ManufacturerPrice,
                    cr.SupplierPrice,SupplierSumNOTAX, ImportMarkup, SupplierMarkup, BatchNumber, ReadyBefore, MadeDate,
                    NDSTax, NDSValue, ReestrPrice, ReestrDate, GTDNumber, CertificateNumber,
                    CertificateDate, CertificateOrgId, RetailMarkup1, cr.RetailPrice, string.Empty, MD, FirstForm.Login,
                    cr.Id, cr.MD);
                if(dt.Count != 1)
                {
                    throw new DIProject.Util.DIException("Ошибка при изменении строки импортируемой накладной");
                }
                sr = dt.Rows[0] as DataSets.waybillsData.SupplierInvoiceLinesUpdateRow;
                if (sr == null)
                    throw new Util.DIException("Ошибка");
                //DataSets.waybillsDataTableAdapters.PartiesUpdateTableAdapter uAdapter = new DIProject.DataSets.waybillsDataTableAdapters.PartiesUpdateTableAdapter();
              //  System.Diagnostics.Debug.WriteLine(sr.PartyId);
               // System.Diagnostics.Debug.WriteLine(MD);
                //System.Threading.Thread.Sleep(50);
              //  Debug.Write("\t\t"); Debug.Write(sr.PartyId); Debug.Write("\t"); Debug.WriteLine(sr.MD.ToLongTimeString() + "\t" + sr.MD.Millisecond.ToString());
             //   pdt = uAdapter.GetData(sr.GoodsId, sr.RetailPrice, sr.BarCode, false, sr.Qntty, string.Empty,
               //     MD, sr.MW, sr.PartyId, sr.MD);                
                return true;
            }
            catch (Exception exc)
            {
                //printRow(sr);
                if (sr != null)
                {
                    Debug.Write(sr.PartyId); Debug.Write("\t"); Debug.Write("MD " + MD + "\t");
                    Debug.WriteLine(sr.MD.ToLongTimeString() + "\t" + sr.MD.Millisecond.ToString());
                }
                MessageBox.Show(exc.ToString());
                return false;
            }
        }
        
        #endregion
        private void printRow(DataRow dr)
        {
            Int32 i = 0;
            System.Text.StringBuilder sb = new StringBuilder();
            foreach (object obj in dr.ItemArray)
            {
                i++;
                sb.Append("Ячейка" + i.ToString()).Append(obj.ToString()).Append("\t");
            }
            System.Diagnostics.Debug.WriteLine(sb.ToString());
        }
        Dictionary.SelectGoods sg = null;
        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {
            return;
            Int32 i = (Int32)cbContragents.ComboBox.SelectedValue;
            if (i == Int32.MinValue)
                return;
            if(sg == null)
                sg = new DIProject.Dictionary.SelectGoods(i);
            sg.toolStripTextBox1.Focus();
            if (sg.ShowDialog() == DialogResult.OK)
            {
                AddWaybillsrecord awr = new AddWaybillsrecord(sg.SelectedGood);
                DialogResult dr1 = awr.ShowDialog();
                if (dr1 == DialogResult.OK)
                {
                    DIProject.Data.Nkld.SupplierInvoiceLinesInsert(CurrendDocId, sg.SelectedGood.GoodsId, null,
                        Convert.ToInt32(awr.txbCount.Text), Util.Convert.ToInt32(awr.txbCount.Text), sg.SelectedGood.Id,
                        Util.Convert.ToDecimal(awr.txbManufacturerPrice.Text), Util.Convert.ToDecimal(awr.txbSupplierPrice.Text),
                        null,
                        Util.Convert.ToDouble(awr.txbImportMarkUp.Text), Util.Convert.ToDouble(awr.txbSupplierMarkUp.Text),
                        awr.txbSerija.Text, Util.Convert.ToDateTime(awr.dtpReadyBefore.Value), Util.Convert.ToDateTime(awr.dtpMadeDate.Value),
                        Convert.ToByte(awr.txbNDSTax.Text), Util.Convert.ToDecimal(awr.txbNDSSumm.Text), Util.Convert.ToDecimal(awr.txbReestrPrice.Text),
                        Util.Convert.ToDateTime(awr.dtpReestrDate.Value), awr.txbGTDNumber.Text, awr.txbCertificateNumber.Text,
                        Util.Convert.ToDateTime(awr.dtpCertificateDate.Value), (Int32)awr.cbCertificateOrg.SelectedValue,
                        Util.Convert.ToDouble(awr.txbMarkUp.Text), Util.Convert.ToDecimal(awr.txbRetailPrice.Text),
                        awr.txbNote.Text, DateTime.Now, FirstForm.Login);
                    lbNaklList_DoubleClick(lbNaklList, EventArgs.Empty);
                }
                awr.Close();
                awr.Dispose();
            }
            //sg.Close();
           // sg.Dispose();
        }

        private void cms_Opening(object sender, CancelEventArgs e)
        {
            if (this.nkldDateGrid.Rows.Count < 1)
            {
                e.Cancel = true;
                return;
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            Int32 ci = (Int32)cbContragents.ComboBox.SelectedValue;
            if(ci == Int32.MinValue)
                return;
            NewNkld n = new NewNkld(ci);
            DialogResult dr = n.ShowDialog();
            if (dr == DialogResult.OK)
            {
                cbContragents_SelectedIndexChanged1(cbContragents, EventArgs.Empty);
            }
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            return;
            if(nkldDateGrid.SelectedRows.Count != 1)
            {
                MessageBox.Show("Нужно выделить позицию", "Ошибка",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            DialogResult dr = MessageBox.Show("Удалить выбранную запись?", "Удаление", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                DataGridViewRow drv = nkldDateGrid.SelectedRows[0];
                DataRowView dd = drv.DataBoundItem as DataRowView;
                DataSets.waybillsData.CurrentNaklRow cnr = dd.Row as DataSets.waybillsData.CurrentNaklRow;
                DataSets.waybillsDataTableAdapters.NklQueries adapter = new DIProject.DataSets.waybillsDataTableAdapters.NklQueries();
                object o = adapter.SupplierInvoiceLinesDelete(cnr.Id, cnr.MD);
                lbNaklList_DoubleClick(lbNaklList, EventArgs.Empty);
            }
        }
        AddRowWithInnerGoods awr;
        private void addInnerGoodsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            Int32 i = (Int32)cbContragents.ComboBox.SelectedValue;
            if (i == Int32.MinValue)
                return;
            if (awr == null)
            {
                awr = new AddRowWithInnerGoods(this.CurrendDocId,this);
            }            
            awr.Show(this);
                         
        }

        private void lbNaklList_SelectedIndexChanged(object sender, EventArgs e)
        {
            AddRowWithInnerGoods.Cache = null;
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            Int32 i = (Int32)cbContragents.ComboBox.SelectedValue;
            if (i == Int32.MinValue)
            {
                MessageBox.Show("Требуется выбрать поставщика!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            NewAssGoodsInputLines nagr = new NewAssGoodsInputLines(this.CurrendDocId,this);
            nagr.MdiParent = this.MdiParent;
            nagr.Show();
        }

        private void delete1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //DeleteNkld();
        }
        private void DeleteNkld()
        {
            if (lbNaklList.SelectedIndex < 0)
            {
                MessageBox.Show("Выберите накладную", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DialogResult dd = MessageBox.Show("Удалить выбранную накладную", "Удаление", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dd != DialogResult.OK)
                return;
            object o = lbNaklList.SelectedItem;
            DataRowView drv = o as DataRowView;
            DataSets.waybillsData.DocumentsRow dr = drv.Row as DataSets.waybillsData.DocumentsRow;
            DataSets.waybillsDataTableAdapters.NklQueries adapter = new DIProject.DataSets.waybillsDataTableAdapters.NklQueries();
            adapter.SupplierInvoiceDocDelete(dr.Id, dr.MD);

        }

        private void nkldDateGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            
            Int32 ci = e.ColumnIndex;
            if (ci < 0)
                return;
            Int32 ri = e.RowIndex;
            if (ri < 0)
                return;
            DataGridViewCell cell;
            DataGridViewRow row = nkldDateGrid.Rows[ri];
            DataRowView drv = row.DataBoundItem as DataRowView;
            DataSets.waybillsData.CurrentNaklRow cur = drv.Row as DataSets.waybillsData.CurrentNaklRow;
            DataGridViewColumn col = nkldDateGrid.Columns[ci];
            if (col.Name =="RetailMarcup")//  ci == 1)
            {
                cell = row.Cells[col.Name];// [1];
                double d = Convert.ToDouble(cell.Value);
                cur.RetailPrice = cur.SupplierPrice * Convert.ToDecimal((1 + d / 100));
                //nkldDateGrid.DataSource = CurrentDataView;
                this.isChange = true;
            }
            if (col.Name=="RetailPrice")// ci == 5)
            {
                cell = row.Cells[col.Name];//[5];
                decimal d = Convert.ToDecimal(cell.Value);
                if (d == 0)
                    return;
                if (!cur.IsSupplierPriceNull())
                {
                    if (cur.SupplierPrice == 0)
                        return;
                    decimal tmp = (d / cur.SupplierPrice - 1) * 100;
                    cur.RetailMarkup = Convert.ToDouble(tmp);
                    //nkldDateGrid.DataSource = CurrentDataView;
                    this.isChange = true;
                }
            }
        }

        

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            Int32 i = (Int32)cbContragents.ComboBox.SelectedValue;
            if (i == Int32.MinValue)
                return;
            if (awr == null)
            {
                awr = new AddRowWithInnerGoods(this.CurrendDocId, this);
            }
            awr.DocId = this.CurrendDocId;
            awr.Show(this);
        }

        private void nkldDateGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            return;
            if (e.RowIndex > -1)
            {
                nkldDateGrid.Rows[e.RowIndex].Selected = true;
                DataRowView drv = nkldDateGrid.SelectedRows[0].DataBoundItem as DataRowView;
                if (drv == null)
                    return;
                DataSets.waybillsData.CurrentNaklRow r = drv.Row as DataSets.waybillsData.CurrentNaklRow;
                if (r == null)
                    return;
                this.Cursor = Cursors.WaitCursor;
                
                AddRowWithInnerGoods arwg = new AddRowWithInnerGoods(r, Util.ActionType.Update);
                arwg.ShowDialog();
                this.Cursor = Cursors.Default;
                lbNaklList_DoubleClick(lbNaklList, EventArgs.Empty);
            }
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            Int32 dId = (Int32)ddlDepart2.ComboBox.SelectedValue;
            Util.PriceCalculation priceCalculation = new DIProject.Util.PriceCalculation(dId);
            foreach (DataRowView drv in this.CurrentData.DefaultView)
            {
                DataSets.waybillsData.CurrentNaklRow cr = drv.Row as DataSets.waybillsData.CurrentNaklRow;
                try
                {
                    if (!cr.IsSupplierPriceNull())
                    {
                        if((!cr.IsGNVLSNull())&& (cr.GNVLS))
                            continue;
                        double dTmp = priceCalculation.Calculate(cr.SupplierPrice); 
                        decimal dcTmp = System.Convert.ToDecimal(1 + dTmp/100);
                        cr.RetailPrice = cr.SupplierPrice * dcTmp;
                        cr.RetailMarkup = dTmp;
                        //cr.RetailMarkup = dTmp;
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                }
            }
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            Int32 dId = (Int32)ddlDepart2.ComboBox.SelectedValue;
            DataSets.waybillsDataTableAdapters.NklQueries query = new DIProject.DataSets.waybillsDataTableAdapters.NklQueries();
            foreach (DataRowView drv in this.CurrentDataView)
            {
                DataSets.waybillsData.CurrentNaklRow cr = drv.Row as DataSets.waybillsData.CurrentNaklRow;
                if (cr == null)
                    continue;
                try
                {
                    object obj = query.previsionPrice(cr.GoodsId,dId);
                    
                    if ((!System.Convert.IsDBNull(obj)) && obj != null)
                    {
                        cr.RetailPrice = Convert.ToDecimal(obj);
                        if (!cr.IsSupplierPriceNull())
                        {
                            decimal d = cr.RetailPrice;
                            if (d == 0)
                                return;

                            if (cr.SupplierPrice == 0)
                                continue;
                            decimal tmp = (d / cr.SupplierPrice - 1) * 100;
                            cr.RetailMarkup = Convert.ToDouble(tmp);
                        }
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                }
            }
        }

        private void btnClearFiltr_Click(object sender, EventArgs e)
        {
            this.CurrentDataView.RowFilter = string.Empty;
            filtrLabel.Text = string.Empty;
            this.CurrentFilter = string.Empty;
            toolStripTextBox1.Text = string.Empty;
        }
        #region сохранение при изменении
        private bool isChange = false;
        private void SaveAll()
        {
            if (isChange)
            {
                DialogResult dr = MessageBox.Show("Данные в накладной изменены. Сохранить?", "Сохранение", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    toolStripButton5_Click(toolStripButton5, EventArgs.Empty);
                }
            }
            isChange = false;
        }
        #endregion

        private void WaybillsImportList_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.SaveAll();
        }

        private void WaybillsImportList_Shown(object sender, EventArgs e)
        {
            cbContragents.SelectedIndexChanged += new EventHandler(cbContragents_SelectedIndexChanged1);
            ddlDepartment.SelectedIndexChanged += new EventHandler(ddlDepartment_SelectedIndexChanged);
            ddlDepart2.SelectedIndexChanged += new EventHandler(ddlDepartments2_SelectedIndexChanged);

        }
        /// <summary>
        /// при изменении департамента пересчитываем цены
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ddlDepartments2_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSets.waybillsData.CurrentNaklDataTable cn = nkldDateGrid.DataSource as DataSets.waybillsData.CurrentNaklDataTable;
            if (cn != null)
            {
                CalculatePrevisionPrice(cn);
            }
        }
        internal void cbContragents_SelectedIndexChanged1(object sender, EventArgs e)
        {
            RefreshNkldList();
        }
        void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshNkldList();
        }
       
        #region печать накладных
        private void fillialPrintToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lbNaklList.SelectedIndex < 0)
            {
                MessageBox.Show("Выберите накладную!");
                return;
            }
            Int32 docId = (Int32)lbNaklList.SelectedValue;
            DataSets.waybillsDataTableAdapters.NKLDInfoTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.NKLDInfoTableAdapter();
            DataSets.waybillsData.NKLDInfoDataTable nkld = adapter.GetData(docId);
            if (nkld.Count != 1)
            {
                MessageBox.Show("Не найдена выбранная накладная");
                return;
            }
            DataSets.Settings.ContragentsRow r;
            DataRowView drv = cbContragents.ComboBox.SelectedItem as DataRowView;
            r = drv.Row as DataSets.Settings.ContragentsRow;
            DataSets.waybillsData.NKLDInfoRow row = nkld.Rows[0] as DataSets.waybillsData.NKLDInfoRow;
            FillialForm ff = new FillialForm();
            DialogResult dRes = ff.ShowDialog();
            if (dRes != DialogResult.OK)
                return;
            FillialNakl fn = new FillialNakl(docId, row.ContragentDocNumber, r.ShortName, row.ContragentDocDate,ff.FillialName,row.DocNumber);
            fn.MdiParent = this.MdiParent;
            fn.Show();
        }
        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lbNaklList.SelectedIndex < 0)
            {
                MessageBox.Show("Выберите накладную!");
                return;
            }
            Int32 docId = (Int32)lbNaklList.SelectedValue;
            DataSets.waybillsDataTableAdapters.NKLDInfoTableAdapter adapter = new DIProject.DataSets.waybillsDataTableAdapters.NKLDInfoTableAdapter();
            DataSets.waybillsData.NKLDInfoDataTable nkld = adapter.GetData(docId);
            if (nkld.Count != 1)
            {
                MessageBox.Show("Не найдена выбранная накладная");
                return;
            }
            DataSets.Settings.ContragentsRow r;
            DataRowView drv = cbContragents.ComboBox.SelectedItem as DataRowView;
            r = drv.Row as DataSets.Settings.ContragentsRow;
            DataSets.waybillsData.NKLDInfoRow row = nkld.Rows[0] as DataSets.waybillsData.NKLDInfoRow;
            PrintNakl pn = new PrintNakl(docId, row.ContragentDocNumber, r.ShortName, row.ContragentDocDate);
            pn.MdiParent = this.MdiParent;
            pn.Show();
        }
        #endregion

        /// <summary>
        /// свойства накладной
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void propertyesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lbNaklList.SelectedIndex < 0)
            {
                MessageBox.Show("Выберите накладную", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            object o = lbNaklList.SelectedItem;
            DataRowView drv = o as DataRowView;
            DataSets.waybillsData.DocumentsRow dr = drv.Row as DataSets.waybillsData.DocumentsRow;
            NaklPropertys np = new NaklPropertys(dr.Id);
            DialogResult dres = np.ShowDialog();
            if (dres == DialogResult.OK)
                np.Close();
            else
                np.Close();
            //adapter.SupplierInvoiceDocDelete(dr.Id, dr.MD);
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            this.RaundPrice1();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Int32 docId = this.CurrendDocId;
            ShiftForm sf = new ShiftForm(docId);
            sf.ShowDialog(this);
        }

    }
}